<?php
$orderServices = new OrdersService();
$orderDetailService = new OrderDetailsService();
$articlerServices = new ArticleService();
$factoryServices = new FactoryServices();
$userService = new UserService();

$fromEmail = $glb['contactEmail'];
$host = Tool::decode($smtp['host'], "sTunnInVietnAm@2012#");
$port = Tool::decode($smtp['port'], "sTunnInVietnAm@2012#");
$user = Tool::decode($smtp['user'], "sTunnInVietnAm@2012#");
$pass = Tool::decode($smtp['pass'], "sTunnInVietnAm@2012#");
$emailService = new EmailService($host, $port, $user, $pass);
$emailService->setSiteURL($glb['websiteURL']);
switch ($action) {
		
	case "add":
		if($permit == true)
		{
			if(isset($_SESSION['orderDetail']))
			{
				$data = array();
				foreach ($_POST as $key => $value) {
					$data[$key] = $value;
				}
				$ordersDomain = new OrdersDomain($data);
				$orderDetailDomain = new OrderdetailsDomain($data);
				$order = new Order($ordersDomain);
				$order->setOrderDetail($orderDetailDomain);
				$orderDetailArr = array();
				$factoryArr = array();
				if(isset($_SESSION['orderDetail']))
				{
					foreach ($_SESSION['orderDetail'] as $orderDetail)
					{
						$orderDetailUn = unserialize($orderDetail);
						$orderDetailUn->getOrderdetailsDomain()->setStt(0);
						$orderDetailArr[] = $orderDetailUn;
						$factoryArr[$orderDetailUn->getOrderdetailsDomain()->getFactoryID()] = '1';
					}
				}
				
				foreach ($orderDetailArr as $orderDetail) {
					$i = 0;
					foreach ($factoryArr as $key => $value)
					{
						if($orderDetail->getOrderdetailsDomain()->getFactoryID() == $key)
						{
							$orderDetail->getOrderdetailsDomain()->setSubOrderNumber(Tool::toAlpha($i));
						}
						$i++;
					}
				}
				$order->setOrderDetail($orderDetailArr);
				$order->getOrdersDomain()->setFactNum(count($factoryArr));
				$order->setOrderDetail($orderDetailArr);
				$orderNumber = $orderServices->getMaxOrderNumber($context, $result) + 1;
				if($orderNumber > $num['orderNumber'])
				{
					$order->getOrdersDomain()->setOrderNumber($orderNumber);
				}
				else {
					$order->getOrdersDomain()->setOrderNumber($num['orderNumber']);
				}
				$order->getOrdersDomain()->setType(2);
				
				$orderID = $orderServices->createOrder($context, $result, $order);
				if($orderID != false)
				{
					$orderFactArr = $orderServices->getPurchaseOrderArr($context, $result, $orderID);
					$reportService = new ReportService();
					$reportService->setSiteURL($glb['websiteURL']);
					foreach ($orderFactArr as $orderF)
					{
						$file = $reportService->generatePDFFile($context, $result, $orderF);
						$fileName = $orderF->getOrdersDomain()->getOrderNumber().'.pdf';
						$orderDetails = $orderF->getOrderDetail();
						$factEmail = $orderDetails[0]->getArticle()->getFactory()->getFactoryDomain()->getEmail();
						$emailService->sendEmailPurchaseOrderToFactory($context, $result, $fromEmail, $factEmail, $orderF->getOrdersDomain()->getOrderID(), $fileName, $file);
					}
					
					$orderFull = $orderServices->getOrderByOid($context, $result, $orderID);
					$file = $reportService->generatePDFFile($context, $result, $orderFull);
					$fileName = $orderFull->getOrdersDomain()->getOrderNumber().'.pdf';
					
					$cusEmail = $orderFull->getConsignee()->getCustomerDomain()->getEmail();
					//$emailService->sendEmailNewOrderToCustomer($context, $result, $fromEmail, $cusMember->getEmail(), $orderID);
					$emailService->sendEmailNewOrderToCustomer($context, $result, $fromEmail, $cusEmail, $orderID, $fileName, $file);
				}
				unset($_SESSION['orderDetail']);
			}
			header("Location:index.php?func=order&opt=list");
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "addOrderCus":
		if($permit == true)
		{
			if(isset($_SESSION['orderDetail']))
			{
				$data = array();
				foreach ($_POST as $key => $value) {
					$data[$key] = $value;
				}
				print_r($data);
				$cusService = new CustomerServices();
				$ordersDomain = new OrdersDomain($data);
				$customer = $cusService->getCustomerByOid($context, $result, $_SESSION['user']['ID']);
				$commTax = $customer->getCustomerDomain()->getComm();
					
				$ordersDomain->setConsignee($_SESSION['user']['ID']);
				$ordersDomain->setCommission($commTax);
				$order = new Order($ordersDomain);
				$orderDetailArr = array();
				$factoryArr = array();
				if(isset($_SESSION['orderDetail']))
				{
					foreach ($_SESSION['orderDetail'] as $orderDetail)
					{
						$orderDetailUn = unserialize($orderDetail);
						$orderDetailUn->getOrderdetailsDomain()->setStt(0);
						$orderDetailArr[] = $orderDetailUn;
						$factoryArr[$orderDetailUn->getOrderdetailsDomain()->getFactoryID()] = '1';
					}
				}
					
				foreach ($orderDetailArr as $orderDetail) {
					$i = 0;
					foreach ($factoryArr as $key => $value)
					{
						if($orderDetail->getOrderdetailsDomain()->getFactoryID() == $key)
						{
							$orderDetail->getOrderdetailsDomain()->setSubOrderNumber(Tool::toAlpha($i));
						}
						$i++;
					}
				}
	
				$order->setOrderDetail($orderDetailArr);
				$order->getOrdersDomain()->setFactNum(count($factoryArr));
				$order->getOrdersDomain()->setType(1);
				$orderID = $orderServices->createOrder($context, $result, $order);
				if($orderID != false)
				{
					//Gui Mail Cho Bart New Order
					
					$userService = new UserService();
					$uDomail = $userService->findByOid($context, $result, $ordersDomain->getConsignee());
	
					$cusMember = $cusService->getCustomerInfoByCusID($context, $result, $uDomail->getCustomerID());
					$emailService->sendEmailNewOrderToBart($context, $result, $cusMember->getEmail(), $fromEmail, $orderID);
				}
				unset($_SESSION['orderDetail']);
			}
			header("Location:index.php?func=order&opt=listOderC");
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "delete":
		if($permit == true)
		{
			if(isset($_GET['id']))
			{
				$orderServices->deleteOrder($context, $result, $_GET['id']);
				header("Location:index.php?func=order&opt=list");
			}
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "editOrder":
		if($permit == true)
		{
			$data = array();
			foreach ($_POST as $key => $value) {
				$data[$key] = $value;
			}
			if(isset($_GET['id']))
			{
				$order = $orderServices->getOrderByOid($context, $result, $_GET['id']);
				$ordersDomain = new OrdersDomain($data);
				$amount = 0;
				$amountFact = 0;
				$currency = '';
				$totalAmountBeforeVAT = 0;
				$totalBart = 0;
				$totalAmount = 0;
				$totalAmountFact = 0;
				$orderDetailArr = $order->getOrderDetail();
				foreach($orderDetailArr as $orderDetail)
				{
					$orderDetailDomain = $orderDetail->getOrderdetailsDomain();					
					$amount += $orderDetailDomain->getAmount();
					$amountFact += $orderDetailDomain->getAmountFact();
					$currency = $orderDetailDomain->getCurrency();
				}
				$totalBart = $amount * ($ordersDomain->getCommission()/100);
				$totalAmountBeforeVAT = $amount + $totalBart;
				$totalAmount = $totalAmountBeforeVAT + ($totalAmountBeforeVAT * ($ordersDomain->getVAT()/100));
				$totalAmountFact = $amountFact + ($amountFact * ($ordersDomain->getVAT()/100));
				if($currency == 'USD')
				{
					$ordersDomain->setSumUSD($totalAmount);
					$ordersDomain->setSumUSDFact($totalAmountFact);
				}
				else
				{
					$ordersDomain->setSumEUR($totalAmount);
					$ordersDomain->setSumEURFact($totalAmountFact);
				}
				$order->setOrdersDomain($ordersDomain);
				$orderServices->updateOrder($context, $result, $order);		
			}
			header("Location:index.php?func=order&opt=view&id=".$_GET['id']);
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "editOrderDetail":
		if($permit == true)
		{
			$data = array();
			foreach ($_POST as $key => $value) {
				$data[$key] = $value;
			}
			
			if(isset($_GET['id']) && is_numeric($_GET['id']) && isset($_GET['cusID']) && is_numeric($_GET['cusID']))
			{
				$order = $orderServices->getOrderByOid($context, $result, $_GET['id']);
				$factNum = $order->getOrdersDomain()->getFactNum();
				$article = $articlerServices->getArticleByCodeByCustomer($context, $result, $data['code'], $_GET['cusID']);
				$factID = $article->getFactory()->getUserDomain()->getID();
				$subOrderNumber = Tool::toAlpha($factNum);
				echo $subOrderNumber;
				$flag = $subOrderNumber;
				if($article != null)
				{
					$ordersDomain = $order->getOrdersDomain();
					$orderDetailArr = $order->getOrderDetail();
					$isExist = false;
					foreach($orderDetailArr as $orderDetail)
					{
						$articleDomain = $orderDetail->getArticle()->getArticleDomain();
						$orderDetailDomain = $orderDetail->getOrderdetailsDomain();
						if($articleDomain->getCode() == $data['code'])
						{
							$orderDetailDomain->setQuantity($orderDetailDomain->getQuantity() + $data['quantity']);
							$orderDetailDomain->setAmount($orderDetailDomain->getQuantity() * $orderDetailDomain->getPrice());
							$orderDetailDomain->setAmountFact($orderDetailDomain->getQuantity() * $orderDetailDomain->getPriceFact());
							$isExist = true;
						}
						if($factID == $orderDetailDomain->getFactoryID())
						{
							$subOrderNumber = $orderDetailDomain->getSubOrderNumber();
						}
					}
					$amount = 0;
					$amountFact = 0;
					$totalPrice = 0;
					$currency = '';
					$totalAmountBeforeVAT = 0;
					$totalBart = 0;
					$totalAmount = 0;
					$totalAmountFact = 0;
					if(!$isExist)
					{
						$articleID = $article->getArticleDomain()->getID();
						$string = 'getPrice' . $data['currency'];
						$string1 = 'getInPrice' . $data['currency'];
						$price = $article->getArticleDomain()->$string();
						$priceFact = $article->getArticleDomain()->$string1();
						
						$dataDetail = array(
											'orderID' 	=> $_GET['id'],
											'articleID' => $articleID,
											'factoryID' => $article->getFactory()->getUserDomain()->getID(),
											'quantity' 	=> $data['quantity'],
											'currency' 	=> $data['currency'],
											'subOrderNumber' => $subOrderNumber,
											'price' 	=> $price,
											'priceFact' 	=> $priceFact,
											'amount' 	=> ($data['quantity'] * $price),
											'amountFact' 	=> ($data['quantity'] * $priceFact),
											'stt'		=>0									
						);
						$orderDetailDomain = new OrderdetailsDomain($dataDetail);
						$orderDetail = new OrderDetail($orderDetailDomain);
						$orderDetail->setArticle($article);
						$orderDetailArr[] = $orderDetail;
					}
					$order->setOrderDetail($orderDetailArr);
					$orderDetailArr = $order->getOrderDetail();
					foreach($orderDetailArr as $orderDetail)
					{
						$orderDetailDomain = $orderDetail->getOrderdetailsDomain();
						$totalPrice += $orderDetailDomain->getPrice();
						$amount += $orderDetailDomain->getAmount();
						$amountFact += $orderDetailDomain->getAmountFact();
						$currency = $orderDetailDomain->getCurrency();
					}
					$totalBart = $amount * ($ordersDomain->getCommission()/100);
					$totalAmountBeforeVAT = $amount + $totalBart;
					$totalAmount = $totalAmountBeforeVAT + ($totalAmountBeforeVAT * ($ordersDomain->getVAT()/100));
					$totalAmountFact = $amountFact + ($amountFact * ($ordersDomain->getVAT()/100));
					if($currency == 'USD')
					{
						$ordersDomain->setSumUSD($totalAmount);
						$ordersDomain->setSumUSDFact($totalAmountFact);
					}
					else
					{
						$ordersDomain->setSumEUR($totalAmount);
						$ordersDomain->setSumEURFact($totalAmountFact);
					}
					if($flag == $subOrderNumber)
					{
						$ordersDomain->setFactNum($factNum + 1);
					}
					$order->setOrdersDomain($ordersDomain);
					$orderServices->updateFullOrder($context, $result, $order);
					header("Location:index.php?func=order&opt=view&id=".$_GET['id']);
				}
				else {
					echo "<script>alert('Article not found!!!');window.location='index.php?func=order&opt=view&id=".$_GET['id']."';</script>";
				}
			}
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "deleteOrderDetail":
		if($permit == true)
		{
			$data = array();
			foreach ($_POST as $key => $value) {
				$data[$key] = $value;
			}
			if(isset($_GET['id']))
			{
				$orderDetail = $orderDetailService->getAllByOid($context, $result, $data['detailID']);
				$subOrderNumber = $orderDetail->getOrderdetailsDomain()->getSubOrderNumber();
				$orderDetailService->deleteOrderDetails($context, $result, $data['detailID']);
				$order = $orderServices->getOrderByOid($context, $result, $_GET['id']);
				$amount = 0;
				$amountFact = 0;
				$currency = '';
				$totalAmountBeforeVAT = 0;
				$totalBart = 0;
				$totalAmount = 0;
				$totalAmountFact = 0;
				$ordersDomain = $order->getOrdersDomain();
				$orderDetailArr = $order->getOrderDetail();
				$flag = false;
				foreach($orderDetailArr as $orderDetail)
				{
					$orderDetailDomain = $orderDetail->getOrderdetailsDomain();
					$amount += $orderDetailDomain->getAmount();
					$amountFact += $orderDetailDomain->getAmountFact();
					$currency = $orderDetailDomain->getCurrency();
					if($orderDetailDomain->getSubOrderNumber() == $subOrderNumber)
					{
						$flag = true;
					}
				}
				$totalBart = $amount * ($ordersDomain->getCommission()/100);
				$totalAmountBeforeVAT = $amount + $totalBart;
				$totalAmount = $totalAmountBeforeVAT + ($totalAmountBeforeVAT * ($ordersDomain->getVAT()/100));
				$totalAmountFact = $amountFact + ($amountFact * ($ordersDomain->getVAT()/100));
				if($currency == 'USD')
				{
					$ordersDomain->setSumUSD($totalAmount);
					$ordersDomain->setSumUSDFact($totalAmountFact);
				}
				else
				{
					$ordersDomain->setSumEUR($totalAmount);
					$ordersDomain->setSumEURFact($totalAmountFact);
				}
				if($flag == false)
				{
					$ordersDomain->setFactNum($ordersDomain->getFactNum() - 1);
				}
				$order->setOrdersDomain($ordersDomain);
				$orderServices->updateOrder($context, $result, $order);
			}
			header("Location:index.php?func=order&opt=view&id=".$_GET['id']);
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "finishEditOrder":
		if($permit == true)
		{
			if(isset($_GET['id']))
			{
				$orderID = $_GET['id'];
				$order = $orderServices->getOrderByOid($context, $result, $orderID);
				$orderNumber = $orderServices->getMaxOrderNumber($context, $result) + 1;
				if($orderNumber > $num['orderNumber'])
				{
					$order->getOrdersDomain()->setOrderNumber($orderNumber);
				}
				else {
					$order->getOrdersDomain()->setOrderNumber($num['orderNumber']);
				}
				$order->getOrdersDomain()->setType(2);
				$orderServices->updateOrder($context, $result, $order);
				// TODO:	gui mail & pdf to customer
				$reportService = new ReportService();
				$reportService->setSiteURL($glb['websiteURL']);
				$file = $reportService->generatePDFFile($context, $result, $order);
				$fileName = $order->getOrdersDomain()->getOrderNumber().'.pdf';
				$emailCus = $order->getConsignee()->getCustomerDomain()->getEmail();
				//$userService = new UserService();
				//$uDomail = $userService->findByOid($context, $result, $order->getOrdersDomain()->getConsignee());
				//$cusService = new CustomerServices();
				//$cusMember = $cusService->getCustomerInfoByCusID($context, $result, $uDomail->getCustomerID());
				//$emailService->sendEmailUpdateOrderToCustomer($context, $result, $fromEmail, $cusMember->getEmail(), $orderID);
				$emailService->sendEmailUpdateOrderToCustomer($context, $result, $fromEmail, $emailCus, $orderID, $fileName, $file);
				// TODO: gui mail & pdf to factory
				$orderFactArr = $orderServices->getPurchaseOrderArr($context, $result, $orderID);
				foreach ($orderFactArr as $orderF)
				{
					$file = $reportService->generatePDFFile($context, $result, $orderF);
					$fileName = $orderF->getOrdersDomain()->getOrderNumber().'.pdf';
					$orderDetails = $orderF->getOrderDetail();
					$factEmail = $orderDetails[0]->getFactory()->getFactoryDomain()->getEmail();
					$emailService->sendEmailPurchaseOrderToFactory($context, $result, $fromEmail, $factEmail, $orderF->getOrdersDomain()->getOrderID(), $fileName, $file);
				}
			}
			header("Location:index.php?func=order&opt=list");
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "confirmCustomerOrder":
		if($permit == true)
		{
			$data = array();
			foreach ($_POST as $key => $value) {
				$data[$key] = $value;
			}
			if(isset($_GET['id']))
			{
				$orderNumber = $data['orderNumber'];
				$factoryID = $data['factoryID'];
				$order = $orderServices->getOrderByOid($context, $result, $_GET['id']);
				$order->getOrdersDomain()->setType(3);
				$order->getOrdersDomain()->setOrderNumber($orderNumber);
				$order->getOrdersDomain()->setFactoryID($factoryID);
				$orderServices->updateOrder($context, $result, $order);
				//send email notification to factory
				$POID = $order->getOrdersDomain()->getOrderID();
				$fact = $userService->findByOid($context, $result, $factoryID);
				$factMember = $factoryServices->getFactoryInfoByFacID($context, $result, $fact->getFactoryID());
				$emailService->sendEmailPurchaseOrderToFactory($context, $result, $fromEmail, $factMember->getEmail(), $POID);
			}
			header("Location:index.php?func=order&opt=list");
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "confirmO":
		if($permit == true)
		{
			if(isset($_POST['orderID']) && $_POST['orderID'] != '' && $_POST['referenceOfCustomer'] != '' && $_POST['otherReference'] != '')
			{
				$orderID = $_POST['orderID'];
				$ref = $_POST['referenceOfCustomer'];
				$otherRef = $_POST['otherReference'];
				$type = 2;
				$orderDomain = $orderServices->getOrderDomainByOrderID($context, $result, $orderID);
				$orderDomain->setReferenceOfCustomer($ref);
				$orderDomain->setOtherReference($otherRef);
				$orderDomain->setType($type);
				$orderServices->updateOrderDomain($context, $result, $orderDomain);
			}
			header("Location:index.php?func=order&opt=listOderC");
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	case "complainO":
		if($permit == true)
		{
			if(isset($_POST['orderID']) && $_POST['orderID'] != '' && $_POST['complain'] != '')
			{
				$orderID = $_POST['orderID'];
				$complainText = addslashes($_POST['complain']);
				$type = 10;
				$orderDomain = $orderServices->getOrderDomainByOrderID($context, $result, $orderID);
				$orderDomain->setComplain($complainText);
				$orderDomain->setType($type);
				$orderServices->updateOrderDomain($context, $result, $orderDomain);
			}
			header("Location:index.php?func=order&opt=listOderC");
		}
		else
		{
			header("Location:index.php?func=dash");
		}
		break;
			
	default:
		echo "khong co tinh nang nay";
		break;
}
?>